package com.hzj.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzj.pojo.VoteItem;
import com.hzj.service.VoteItemService;
import com.hzj.service.VoteOptionService;
import com.hzj.service.VoteSubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hzj
 * @since 2021-03-19
 */
@Controller
public class VoteItemController {
    @Autowired
    VoteItemService vis;
    @Autowired
    VoteSubjectService vss;
    @Autowired
    VoteOptionService vos;

    @RequestMapping("/NoPermission")
    @ResponseBody
    public String NoPermission() {
        return "你已经投过票了，无法重复投票";
    }

    @PostMapping("/addVoteItem")
    public String addVoteItem(Model model, VoteItem voteItem, Long[] options) {
        QueryWrapper wrapper = new QueryWrapper();
        Map<String, Object> map = new HashMap<>();
        map.put("vu_user_id", voteItem.getVuUserId());
        map.put("vs_id", voteItem.getVsId());
        wrapper.allEq(map);
        List list = vis.list(wrapper);
        System.out.println("是否投票集合=============>" + list);
        if (list.size() > 0) {
            return "forward:NoPermission";
        }
//        System.out.println(voteItem);
        List<VoteItem> voteItemList = new ArrayList<>();
        for (int i = 0; i < options.length; i++) {
            Long option = options[i];
            voteItemList.add(new VoteItem(voteItem.getVuUserId(), voteItem.getVsId(), option));
//            System.out.println(option);
        }

//        System.out.println("投票集合===============》" + voteItemList);
        boolean b = vis.insertVoteItemList(voteItemList);
        if (!b) {
            return "forward:/checkSubject?id=" + voteItem.getVsId();
        }
        return "forward:/showList";
    }

    @GetMapping("/admin/deleteVoteAll")
    public String deleteVoteAll( Long vsid, Model model) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("vs_id", vsid);
        boolean remove = vis.remove(wrapper);
        boolean remove1 = vos.remove(wrapper);
        boolean remove2 = vss.remove(wrapper);
        if (remove && remove1 && remove2) {
            return "redirect:/showList?updateKey=" + 1;
        }
        model.addAttribute("errorUpdate", "删除失败，请刷新页面重试");
        return "forward:/showList?updateKey=" + 1;
    }

}

